package com.lzj.demo.jdbc;

import cn.hutool.core.io.resource.ClassPathResource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.*;
import java.util.Objects;
import java.util.Properties;

public class DBUtils {
    /**
     * 获取数据连接
     * 从配置文件读取数据库连接信息
     * @author kaikaiking
     * */
    public static Connection getConnection() throws Exception {
        //获取定义在src/main/resources文件夹中的配置文件
        ClassPathResource resource = new ClassPathResource("druid.properties");
        //加载配置文件
        Properties prop = new Properties();
        prop.load(resource.getStream());
        //获取连接池对象
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
        //获取数据库连接 Connection
        return dataSource.getConnection();
    }

    /**
     * 获取数据连接
     * @author kaikaiking
     * */
    public static Connection getConnection2()throws Exception{
        //注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //获取连接
        String url = "jdbc:mysql://120.76.73.12:3306/db1?useSSL=false&useServerPrepStmts=true&characterEncoding=utf8";
        String username = "root";
        String password = "";
        return DriverManager.getConnection(url, username, password);
    }

    /**
     * 关闭连接资源
     *
     * @param rs
     * @param state
     * @param conn
     * @author kaikaiking
     */
    public static void close(ResultSet rs, Statement state, Connection conn) {
        try {
            if (Objects.nonNull(rs)) {
                rs.close();
            }
            if (Objects.nonNull(state)) {
                state.close();
            }
            if (Objects.nonNull(conn)) {
                conn.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
